package jjn.carl.dp;

import java.util.Scanner;

/**
 * @author Jjn
 * @since 2023/8/6 15:04
 */
public class LeetCode63 {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int height = obstacleGrid.length, width = obstacleGrid[0].length;
        int[][] dp = new int[height][width];
        for (int i = 0; i < height; i++) {
            if (obstacleGrid[i][0] == 1) {
                for (int j = i; j < height; j++) {
                    dp[j][0] = 0;
                    i = j;
                }
            } else {
                dp[i][0] = 1;
            }
        }
        for (int i = 0; i < width; i++) {
            if (obstacleGrid[0][i] == 1) {
                for (int j = i; j < width; j++) {
                    dp[0][j] = 0;
                    i = j;
                }
            } else {
                dp[0][i] = 1;
            }
        }
        for (int i = 1; i < height; i++) {
            for (int j = 1; j < width; j++) {
                if (obstacleGrid[i][j] == 1) {
                    dp[i][j] = 0;
                } else {
                    dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
                }
            }
        }
        return dp[height - 1][width - 1];
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int height = scanner.nextInt();
        int width = scanner.nextInt();
        int[][] obstacleGrid = new int[height][width];
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                obstacleGrid[i][j] = scanner.nextInt();
            }
        }
        int uniquePathsWithObstacles = new LeetCode63().uniquePathsWithObstacles(obstacleGrid);
        System.out.println(uniquePathsWithObstacles);
    }
}
